#include "rio.h"
#include "socket_utils.h"
#define MAXLINE 100
int main(int argc, char **argv)
{
  char buf[MAXLINE];
  char *hostname = "127.0.0.1";
  int port, clientfd;
  size_t n;
  rio_t rio;
  if (argc == 3) {
    hostname = argv[1];
    port = atoi(argv[2]);
  } else if (argc == 2)
    port = atoi(argv[1]);
  else {
    fprintf(stderr, "usage: %s <host> <port>\n", argv[0]);
    exit(0);
  }
  clientfd = open_clientfd(hostname, port);
  if (clientfd < 0) {
    fprintf(stderr, "error open socket\n");
    exit(0);
  }
  rio_readinitb(&rio, clientfd);
  while (fgets(buf, MAXLINE, stdin) != NULL) {
    rio_writen(clientfd, buf, strlen(buf));
    rio_readlineb(&rio, buf, MAXLINE);
    fputs(buf, stdout);
  }
  close(clientfd);
  return 0;
}
